<template>
    <div>
        <!-- 面包屑导航区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>参数列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片视图区域 -->
        <el-card>
            <!-- 警告区域 -->
            <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon :closable='false'>
            </el-alert>

            <!-- 商品分类区域 -->
            <el-row class="cat-opt">
                <el-col>
                    <span>选择商品分类：
                        <el-cascader v-model="selectedKeys" :options="catelist" :props="cascaderProps"
                            @change="handleChanged" clearable collapse-tags></el-cascader>
                    </span>
                </el-col>
            </el-row>

            <!-- tab页签区域 -->
            <el-tabs v-model="activeName" @tab-click="handleTabClick">
                <!-- 添加动态参数面板 -->
                <el-tab-pane label="动态参数" name="many">
                    <el-button type="primary" :disabled="isBtnDisabled" @click="addDialogVisible = true">添加参数
                    </el-button>
                    <el-table :data="manyDataCate" style="width: 100%" border stripe>
                        <!-- 展开行expand -->
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <!-- for循环遍历tag标签 -->
                                <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index" closable
                                    @close="handleClose(index,scope.row)">
                                    {{item}}
                                </el-tag>
                                <!-- 文本输入框 -->
                                <el-input class="input-new-tag" v-if="scope.row.inputVisible"
                                    v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                                    @keyup.enter.native="handleInputConfirm(scope.row)"
                                    @blur="handleInputConfirm(scope.row)">
                                </el-input>
                                <!-- 按钮 -->
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+
                                    New Tag
                                </el-button>
                            </template>
                        </el-table-column>
                        <el-table-column prop="attr_name" label="参数名称"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button type="primary" icon="el-icon-edit" @click="showEditCate(scope.row)">修改
                                </el-button>
                                <el-button type="danger" icon="el-icon-delete" @click="deleteCate(scope.row.attr_id)">删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <!-- 添加静态属性面板 -->
                <el-tab-pane label="静态属性" name="only">
                    <el-button type="primary" :disabled="isBtnDisabled" @click="addDialogVisible = true">添加属性
                    </el-button>
                    <el-table :data="onlyDataCate" style="width: 100%" border stripe>
                        <!-- 展开行expand -->
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <!-- for循环遍历tag标签 -->
                                <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index" closable
                                    @close="handleClose(index,scope.row)">
                                    {{item}}
                                </el-tag>
                                <!-- 文本输入框 -->
                                <el-input class="input-new-tag" v-if="scope.row.inputVisible"
                                    v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                                    @keyup.enter.native="handleInputConfirm(scope.row)"
                                    @blur="handleInputConfirm(scope.row)">
                                </el-input>
                                <!-- 按钮 -->
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+
                                    New Tag
                                </el-button>
                            </template>
                        </el-table-column>
                        <el-table-column prop="attr_name" label="属性名称"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button type="primary" icon="el-icon-edit" @click="showEditCate(scope.row)">修改
                                </el-button>
                                <el-button type="danger" icon="el-icon-delete" @click="deleteCate(scope.row.attr_id)">删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>

        <!-- 添加参数对话框 -->
        <el-dialog :title="'添加'+cateTitle" :visible.sync="addDialogVisible" width="50%" @close="addCateDialogClosed">
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
                <el-form-item :label="cateTitle" prop="attr_name">
                    <el-input v-model="addForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveAddCate">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 修改对话框 -->
        <el-dialog :title="'修改'+cateTitle" :visible.sync="editDialogVisible" width="50%" @close="editCateDialogClosed">
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
                <el-form-item :label="cateTitle" prop="attr_name">
                    <el-input v-model="editForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEditCate">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                //商品分类列表
                catelist: [],
                // 级联选择框
                cascaderProps: {
                    value: 'cat_id',
                    label: 'cat_name',
                    children: 'children'
                },
                // 级联选择框双向绑定的数组
                selectedKeys: [],
                activeName: 'many',
                //动态参数
                manyDataCate: [],
                //静态参数
                onlyDataCate: [],
                addDialogVisible: false,
                addForm: {
                    attr_name: ''
                },
                addFormRules: {
                    attr_name: [{
                        required: true, message: '请输入参数名称', trigger: 'blur'
                    }]
                },
                editDialogVisible: false,
                editForm: {
                    attr_name: '',
                    id: '',
                    attrId: '',
                    attr_sel: ''
                },
                editFormRules: {
                    attr_name: [{
                        required: true, message: '请输入参数名称', trigger: 'blur'
                    }]
                }
            }
        },
        created() {
            this.getCateList()
        },
        methods: {
            async getCateList() {
                const { data: res } = await this.$http.get('categories')
                if (res.meta.status !== 200) return this.$message.error('获取分类数据列表失败')
                this.catelist = res.data
            },
            // 监听级联选择框变化的函数
            handleChanged() {
                this.getParamsData()
            },
            // 点击标签页发生动态改变
            handleTabClick() {
                this.getParamsData()
            },
            // 获取参数的列表数据
            async getParamsData() {
                // 选中的不是三级分类
                if (this.selectedKeys.length !== 3) {
                    this.selectedKeys = []
                    this.manyDataCate = []
                    this.onlyDataCate = []
                    return
                }
                const { data: res } = await this.$http.get('categories/' + this.cateId + '/attributes', { params: { sel: this.activeName } })
                if (res.meta.status !== 200) {
                    return this.$message.error('获取数据失败')
                }
                res.data.forEach(item => {
                    item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
                    item.inputVisible = false
                    item.inputValue = ''
                })
                console.log(res);
                if (this.activeName === 'many') {
                    this.manyDataCate = res.data
                } else {
                    this.onlyDataCate = res.data
                }
            },
            //添加参数行为
            addCateDialogClosed() {
                this.$refs.addFormRef.resetFields()
            },
            saveAddCate() {
                this.$refs.addFormRef.validate(async valid => {
                    if (!valid) return
                    const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
                        attr_name: this.addForm.attr_name,
                        attr_sel: this.activeName
                    })
                    if (res.meta.status !== 201) return this.$message.error('添加失败')
                    this.$message.success('添加成功')
                    this.getParamsData()
                    this.addDialogVisible = false
                })
            },
            //编辑参数行为
            editCateDialogClosed() {
                this.$refs.editFormRef.resetFields()
            },
            showEditCate(cate) {
                this.editForm.attr_name = cate.attr_name
                this.editForm.attrId = cate.attr_id
                this.editForm.attr_sel = cate.attr_sel
                this.editDialogVisible = true
            },
            saveEditCate() {
                this.$refs.editFormRef.validate(async valid => {
                    if (!valid) return
                    const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attrId}`, {
                        attr_name: this.editForm.attr_name,
                        attr_sel: this.editForm.attr_sel
                    })
                    if (res.meta.status !== 200) return this.$message.error('提交修改失败')
                    this.getParamsData()
                    this.$message.success('提交修改成功')
                    this.editDialogVisible = false
                })
            },
            //删除参数操作
            async deleteCate(id) {
                const ret = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(error => error)
                if (ret !== 'confirm') return this.$message.info('已取消删除')
                const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
                if (res.meta.status !== 200) return this.$message.error('删除参数失败')
                this.$message.success('删除参数成功')
                this.getParamsData()
            },
            //保存attr_vals修改的数据
            async saveAttrValCate(row) {
                const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}}`, {
                    attr_name: row.attr_name,
                    attr_sel: row.attr_sel,
                    attr_vals: row.attr_vals.join(',')
                })
                if (res.meta.status !== 200) return this.$message.error('编辑参数失败')
                this.$message.success('编辑参数成功')
            },
            //按下回车键或者失去焦点都可以触发
            handleInputConfirm(row) {
                console.log(row);
                if (row.inputValue.trim().length === 0) {
                    row.inputValue = ''
                    row.inputVisible = false
                    return
                }
                //否则输入框已经有内容
                row.attr_vals.push(row.inputValue.trim())
                row.inputValue = ''
                row.inputVisible = false
                //发起请求保存数据到服务器
                this.saveAttrValCate(row)
            },
            //显示输入框
            showInput(item) {
                item.inputVisible = true
                //让文本框自动获得焦点
                //$nextTick方法的作用，就是当页面上的元素被重新渲染之后，才会执行回调函数中的代码
                this.$nextTick(_ => {
                    this.$refs.saveTagInput.$refs.input.focus()
                });
            },
            // 删除元素
            handleClose(i, row) {
                row.attr_vals.splice(i, 1)
                this.saveAttrValCate(row)
            }

        },
        computed: {
            // 如果按钮被禁用，返回true，否则返回false
            isBtnDisabled() {
                if (this.selectedKeys.length !== 3) {
                    return true
                }
                return false
            },
            cateId() {
                if (this.selectedKeys.length == 3) {
                    return this.selectedKeys[2]
                }
                return null
            },
            cateTitle() {
                if (this.activeName == 'many') {
                    return '动态参数'
                }
                return '静态属性'
            }
        }
    }
</script>

<style lang="less" scoped>
    .cat-opt {
        margin: 15px 0;
    }

    .el-tag {
        margin: 5px;
    }

    .input-new-tag {
        width: 120px;
    }
</style>